package com.jushu.storbox.actions;

import java.io.File;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.jushu.storbox.FileDownloadActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.ViewActivity;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.ShareINode;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.network.WifiController;
import com.jushu.storbox.service.ServiceFactory;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.image.ImageUtils;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.vo.PagedList;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.MoveFileRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.INodeShareV2;
import com.huawei.sharedrive.sdk.android.serviceV2.FileClientV2;

public class FileAction extends BaseAction {

	private final static String TAG = FileAction.class.getName();

	public void searchFileListFromServer(final String ownerId,
			final String keyWords, final int pageNo, final Context context,
			final Handler messageHandler) {
		LogUtil.i(TAG, "searchFileListFromServer[Actions]");
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				PagedList<FileFolderInfo> resource = ServiceFactory
						.getRemoteFileService().searchNodeListFromServer(
								context, ownerId, keyWords,
								PublicTools.getDes(context),
								PublicTools.getOrderBy(context), pageNo,
								messageHandler);
				Message resourceMsg = new Message();
				resourceMsg.what = UiConstant.NODE_SEARCH_BY_KEYWORD;
				resourceMsg.obj = resource;
				messageHandler.sendMessage(resourceMsg);

				LogUtil.i(TAG, "getAllFileListFromServer success[Actions]");
			}
		});
	}

	public void getNodeListFromServer(final String ownerId,
			final String folderId, final int pageNo, final Context context,
			final Handler messageHandler) {
		LogUtil.i(TAG, "getNodeListFromServer[Actions]");
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				PagedList<FileFolderInfo> resource = ServiceFactory
						.getRemoteFileService().getNodeListFromServer(context,
								ownerId, folderId, PublicTools.getDes(context),
								PublicTools.getOrderBy(context), pageNo,
								messageHandler);
				Message resourceMsg = new Message();
				resourceMsg.what = MessageCode.LOAD_FILE_LIST;
				resourceMsg.obj = resource;
				messageHandler.sendMessage(resourceMsg);

				LogUtil.i(TAG, "getAllFileListFromServer success[Actions]");
			}
		});
	}

	public void deleteFile(final Context context,
			final FileFolderInfo fileInformation, final Handler messageHandler) {
		LogUtil.i(TAG, "deleteAllFile[Actions]");
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			@Override
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				ServiceFactory.getRemoteFileService().deleteFile(
						fileInformation);
				ServiceFactory.instance(context).getLocalFileService()
						.deleteFile(fileInformation);
				Message resourceMsg = new Message();
				resourceMsg.what = MessageCode.DELETE_FILE_SUCCESS;
				resourceMsg.obj = fileInformation;
				messageHandler.sendMessage(resourceMsg);
			}
		});
	}

	public void renameFile(final String fileName,
			final FileFolderInfo fileInformation, final Context context,
			final Handler messageHandler) {
		LogUtil.i(TAG, "renameFolder[Actions]");
		executeRunTask(new RealTaskRunnable(context, messageHandler) {

			@Override
			protected void doTask(Context context, Handler msgHandler)

					throws ClientException {
				FileInfoResponseV2 fileInfoResponse = ServiceFactory
						.getRemoteFileService().renameFile(fileInformation,
								fileName);
				if (ImageUtils.isImageType(fileInformation.getName())) {
					DirectoryUtil.deleteFileThumbnailPath(context,
							fileInformation.getOwnerBy(),
							fileInformation.getId(), fileInformation.getName());
				}
				FileFolderInfo info = new FileInfo();
				info.valueOf(fileInfoResponse);
				DAOFactory.instance(context).getFileDao().rename(info, fileName);
				
				fileInformation.setName(fileName);
				fileInformation.setLastUpdateDate(info.getLastUpdateDate());
				Message msg = new Message();
				msg.obj = fileInformation;
				msg.what = MessageCode.RENAME_SUCCESS;
				messageHandler.sendMessage(msg);
			}
		});
	}
	
	public void getNodeInfomationFromServer(final Context context,
			final INodeShareV2 node, final Handler messageHandler) {
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			@Override
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				ShareINode resource = new ShareINode();
//				resource.valueOf(node);
				resource.setOwnerId(node.getOwnerId()+"");
				resource.setId(node.getNodeId()+"");
				FileInfoResponseV2 fileInfoResponse = ServiceFactory
						.getRemoteFileService().getFileResponse(resource);
				FileInfo info = new FileInfo();
				info.valueOf(fileInfoResponse);
				Message msg = new Message();
				msg.obj = info;
				msg.what = UiConstant.FILE_ACTION_GET_NODE_INFOMATION;
				messageHandler.sendMessage(msg);
			}
		});
	}

	public void moveFile(final Context context, final int messageCode,
			final FileFolderInfo sourceNode, final String targetFolderId,
			final String targetFolderOwnerId, final Handler messageHandler) {
		executeRunTask(new RealTaskRunnable(context, messageHandler) {

			protected void doTask(Context context, Handler msgHandler)

					throws ClientException {
				MoveFileRequestV2 request = new MoveFileRequestV2();
				request.setDestParent(Long.valueOf(targetFolderId));
				request.setAutoRename(false);
				request.setDestOwnerId(Long.valueOf(targetFolderOwnerId));
				FileInfoResponseV2 response = FileClientV2.getInstance().moveFileForObject(sourceNode.getOwnerId(),
						sourceNode.getId(), request, getAuthCode());
				FileInfo info = new FileInfo();
				info.valueOf(response);
				DAOFactory.instance(context).getFileDao().updateFile(response, false, false);
				Message msg = messageHandler.obtainMessage();
				msg.what = messageCode;
				msg.obj = sourceNode;
				msg.sendToTarget();
			}

			@Override
			protected boolean filterException(ClientException e, final Handler handler) {
				if(e.getStatusCode() == ClientExceptionRelateHandler.ERROR_CODE_409_SOURCE_CONFLICT
						&& ClientExceptionRelateHandler.RepeatNameConflict.equals(e.getCode())) {
		            handler.post(new Runnable(){
						@Override
						public void run() {
							final ClouddriveDialog move = new ClouddriveDialog(context, R.style.dialog_upload,
					                R.layout.dialog_filedelete);
				            View conventView = move.getConventView();
				            Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
				            Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);
				            TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
				            dialog_prompt_tv.setText(context.getString(R.string.allfile_confirm_reanme_filefolder));
				            dialog_cancal.setOnClickListener(new View.OnClickListener() {
				                @Override
				                public void onClick(View v) {
				                	move.dismiss();	//单个文件移动取消自动重命名
				                	handler.sendEmptyMessage(UiConstant.NODE_ACTION_MOVE_CANCEL);
				                }
				            });
				            dialog_OK.setOnClickListener(new View.OnClickListener() {
				                @Override
				                public void onClick(View v) {
				                	move.dismiss();
				                	moveFileWithAutoRename(context, messageCode, sourceNode, targetFolderId, targetFolderOwnerId, handler);
				                }
				            });
				            move.show();
						}
		            });
					return true;
				} else {
					return false;
				}
				
			}
			
		});
	}
	
	
	
	public void moveFileWithAutoRename(final Context context, final int messageCode,
			final FileFolderInfo sourceNode, final String targetFolderId,
			final String targetFolderOwnerId, final Handler messageHandler) {
		executeRunTask(new RealTaskRunnable(context, messageHandler) {

			protected void doTask(Context context, Handler msgHandler)

					throws ClientException {
				MoveFileRequestV2 request = new MoveFileRequestV2();
				request.setDestParent(Long.valueOf(targetFolderId));
				request.setAutoRename(true);
				request.setDestOwnerId(Long.valueOf(targetFolderOwnerId));
				FileInfoResponseV2 response = FileClientV2.getInstance().moveFileForObject(sourceNode.getOwnerId(),
						sourceNode.getId(), request, getAuthCode());
				FileInfo info = new FileInfo();
				info.valueOf(response);
				DAOFactory.instance(context).getFileDao().updateFile(response, false, false);

				Message msg = messageHandler.obtainMessage();
				msg.what = messageCode;
				msg.obj = sourceNode;
				msg.sendToTarget();
			}
		});
	}

	public void openFile(final Context context,

			final FileFolderInfo sourceNode, final Handler messageHandler) {

		final String path = DirectoryUtil.generateFileDownloadPath(context,
				sourceNode.getOwnerId(), sourceNode.getId(),
				sourceNode.getName());
		File file = new File(path);
		if (file.exists()) {
			if (PublicTools.isFileType(path, Constant.MUSIC_TYPE)) {
                Intent intent = new Intent(context, FileDownloadActivity.class);
                Log.i("liuxiang", sourceNode + "viewHolder.fileInformation");
                intent.putExtra(ClientConfig.FILE_FOLDER_INFO, sourceNode);
                intent.putExtra("isMusic", true);
                context.startActivity(intent);
                ((Activity) context).overridePendingTransition(R.anim.right_in,  R.anim.left_out);
            } else {
				Intent intent = new Intent(context, ViewActivity.class);
				intent.putExtra("view_mdm_path", path);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
            }
		} else {
//			Intent intent = new Intent(context, FileDownloadActivity.class);
//			intent.putExtra(ClientConfig.FILE_FOLDER_INFO, sourceNode);
//			context.startActivity(intent);
			
			WifiController wifiController = ShareDriveApplication.getInstance().getWifiController();
            if (ClientConfig.NETWORK_ISWIFI.equals(wifiController.getWifiType()) || !PublicTools.getDownloadRemind(context)) {
            	Intent intent = new Intent(context, FileDownloadActivity.class);
                intent.putExtra(ClientConfig.FILE_FOLDER_INFO, sourceNode);
                context.startActivity(intent);
                ((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
            } else {
                final ClouddriveDialog menuDialog = new ClouddriveDialog(context, R.style.myDialogTheme, R.layout.window_wifi_dialog);
                menuDialog.setHeigth(LayoutParams.MATCH_PARENT);
                menuDialog.setWidth(LayoutParams.MATCH_PARENT);
                menuDialog.setCanceledOnTouchOutside(true);
                menuDialog.show();
                View conventView = menuDialog.getConventView();
                Button confirmBt = (Button) conventView.findViewById(R.id.confirm_btn);
                Button cancleBt = (Button) conventView.findViewById(R.id.cancle_btn);
                
                confirmBt.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        menuDialog.dismiss();
                        Intent intent = null;
                		intent = new Intent(context, FileDownloadActivity.class);
                        intent.putExtra(ClientConfig.FILE_FOLDER_INFO, sourceNode);
                        context.startActivity(intent);
                        ((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
                    }
                });
                cancleBt.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        menuDialog.dismiss();
                    }
                });
            }
		}
	}
}
